<template>
  <view class="history-container">
    <!-- 顶部导航栏 -->
    <view v-if="showNavbar" class="header">
      <view class="header-left">
        <text class="back-icon" @click="goBack">‹</text>
      </view>
      <view class="header-center">
        <text class="app-name">历史对话</text>
      </view>
      <view class="header-right">
        <text class="clear-icon" @click="showClearConfirm">🗑</text>
      </view>
    </view>

    <!-- 小程序模式：顶部状态栏 -->
    <view v-if="!showNavbar" class="mp-header">
      <view class="mp-status-bar"></view>
      <view class="mp-nav">
        <text class="mp-back" @click="goBack">‹</text>
        <text class="mp-title">历史对话</text>
        <text class="mp-clear" @click="showClearConfirm">🗑</text>
      </view>
    </view>

    <!-- 对话列表 -->
    <scroll-view 
      class="chat-list" 
      :class="{ 'chat-list-mp': !showNavbar }"
      scroll-y="true"
      v-if="chatHistory.length > 0"
    >
      <view 
        v-for="chat in sortedChatHistory" 
        :key="chat.id" 
        class="chat-item"
        :class="{ 'chat-item-active': chat.id === currentChatId }"
        @click="selectChat(chat)"
      >
        <view class="chat-item-content">
          <view class="chat-title">{{ chat.title }}</view>
          <view class="chat-preview">
            <text class="chat-message-count">{{ chat.messages.length }} 条消息</text>
            <text class="chat-time">{{ formatTime(chat.updatedAt) }}</text>
          </view>
        </view>
        <view class="chat-actions">
          <text class="action-icon" @click.stop="editChatTitle(chat)">✏️</text>
          <text class="action-icon" @click.stop="deleteChat(chat.id)">🗑️</text>
        </view>
      </view>
    </scroll-view>

    <!-- 空状态 -->
    <view v-else class="empty-state">
      <text class="empty-icon">💬</text>
      <text class="empty-title">暂无历史对话</text>
      <text class="empty-desc">开始新的对话吧</text>
      <button class="start-chat-btn" @click="startNewChat">开始对话</button>
    </view>

    <!-- 清空确认弹窗 -->
    <view v-if="showClearDialog" class="dialog-overlay" @click="hideClearConfirm">
      <view class="dialog-content" @click.stop>
        <view class="dialog-header">
          <text class="dialog-title">确认清空</text>
        </view>
        <view class="dialog-body">
          <text class="dialog-message">选择要执行的操作：</text>
        </view>
        <view class="dialog-actions">
          <view class="dialog-actions-row">
            <button class="dialog-btn dialog-btn-sync" @click="forceSync">强制同步</button>
            <button class="dialog-btn dialog-btn-clean" @click="cleanEmptyChats">清理空对话</button>
          </view>
          <view class="dialog-actions-row">
          <button class="dialog-btn dialog-btn-cancel" @click="hideClearConfirm">取消</button>
            <button class="dialog-btn dialog-btn-confirm" @click="clearAllChats">清空所有</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 编辑标题弹窗 -->
    <view v-if="showEditDialog" class="dialog-overlay" @click="hideEditDialog">
      <view class="dialog-content" @click.stop>
        <view class="dialog-header">
          <text class="dialog-title">编辑标题</text>
        </view>
        <view class="dialog-body">
          <input 
            class="title-input" 
            v-model="editingTitle" 
            placeholder="请输入对话标题"
            maxlength="50"
          />
        </view>
        <view class="dialog-actions">
          <button class="dialog-btn dialog-btn-cancel" @click="hideEditDialog">取消</button>
          <button class="dialog-btn dialog-btn-confirm" @click="confirmEditTitle">确认</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { useChatStore } from '../../store/chat.js'

export default {
  data() {
    return {
      showClearDialog: false,
      showEditDialog: false,
      editingChat: null,
      editingTitle: '',
      showNavbar: false
    }
  },
  
  computed: {
    chatStore() {
      return useChatStore()
    },
    chatHistory() {
      return this.chatStore?.chatHistory || []
    },
    currentChatId() {
      return this.chatStore?.currentChatId || null
    },
    sortedChatHistory() {
      return [...this.chatHistory].sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
    }
  },
  
  onLoad() {
    // 根据平台控制导航栏显示
    // #ifdef H5 || APP-PLUS
    this.showNavbar = true
    // #endif
    // #ifdef MP-WEIXIN
    this.showNavbar = false
    // #endif
    // #ifndef H5 || APP-PLUS || MP-WEIXIN
    this.showNavbar = false
    // #endif
    
    // 延迟加载历史数据，确保store已初始化
    this.$nextTick(() => {
      if (this.chatStore) {
        this.chatStore.loadFromStorage()
        // 温和地清理空对话（只在有空对话时才清理）
        this.chatStore.removeEmptyChatsIfAny()
        // 同时从服务器同步最新数据
        this.syncHistoryFromServer()
      }
    })
  },
  
  methods: {
    // 从服务器同步历史记录
    async syncHistoryFromServer() {
      try {
        if (this.chatStore && this.chatStore.syncFromServer) {
          uni.showLoading({
            title: '同步历史记录...',
            mask: false
          })
          
          await this.chatStore.syncFromServer()
          
          uni.hideLoading()
          console.log('历史记录同步完成')
        }
      } catch (error) {
        console.error('同步历史记录失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: '同步失败',
          icon: 'none',
          duration: 2000
        })
      }
    },

    // 强制同步并清理
    async forceSync() {
      try {
        uni.showLoading({
          title: '强制同步中...',
          mask: true
        })

        if (this.chatStore) {
          // 先清理本地空对话
          const localCleanCount = this.chatStore.cleanEmptyChats()
          console.log(`本地清理了 ${localCleanCount} 个空对话`)

          // 强制从服务器同步
          await this.chatStore.syncFromServer()

          // 再次清理确保数据一致性
          const finalCleanCount = this.chatStore.removeEmptyChatsIfAny()
          console.log(`最终清理了 ${finalCleanCount} 个空对话`)
        }

        uni.hideLoading()
        uni.showToast({
          title: '同步完成',
          icon: 'success'
        })
      } catch (error) {
        console.error('强制同步失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: '同步失败',
          icon: 'none'
        })
      }
    },
    
    goBack() {
      // 使用安全导航工具
      this.safeNavigateBack()
    },

    // 安全的返回上一页
    safeNavigateBack(fallbackUrl = '/pages/index/index') {
      try {
        const pages = getCurrentPages()
        console.log('历史页面返回，当前页面栈:', pages.length)
        
        if (pages.length > 1) {
          // 有上一页，可以安全返回
          uni.navigateBack({
            success: () => {
              console.log('历史页面返回成功')
            },
            fail: (err) => {
              console.error('历史页面返回失败:', err)
              // 返回失败时跳转到fallback页面
              uni.reLaunch({
                url: fallbackUrl
              })
            }
          })
        } else {
          // 没有上一页，跳转到首页
          console.log('历史页面没有上一页，跳转到首页')
          uni.reLaunch({
            url: fallbackUrl
          })
        }
      } catch (error) {
        console.error('历史页面导航检查失败:', error)
        // 出现异常时安全跳转
        uni.reLaunch({
          url: fallbackUrl
        })
      }
    },
    
    selectChat(chat) {
      if (this.chatStore) {
        this.chatStore.switchToChat(chat.id)
      }
      uni.navigateTo({
        url: '/pages/Questions/questions'
      })
    },
    
    startNewChat() {
      // 不在历史记录页面创建新对话，直接跳转到首页
      // 新对话会在用户实际发送消息时创建
      console.log('历史页面跳转到首页')
      uni.reLaunch({
        url: '/pages/index/index'
      })
    },
    
    deleteChat(chatId) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个对话吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              // 找到要删除的对话
              const chat = this.chatHistory.find(c => c.id === chatId)
              
            if (this.chatStore) {
              this.chatStore.deleteChat(chatId)
            }
              
              // 如果有sessionId，可以选择同时删除服务器记录
              if (chat && chat.sessionId) {
                try {
                  // 这里可以调用删除服务器会话的API
                  // await deleteSession(chat.sessionId)
                  console.log('本地对话已删除，sessionId:', chat.sessionId)
                } catch (serverError) {
                  console.warn('删除服务器会话失败:', serverError)
                  // 即使服务器删除失败，本地删除成功也算成功
                }
              }
              
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            } catch (error) {
              console.error('删除对话失败:', error)
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    showClearConfirm() {
      this.showClearDialog = true
    },
    
    hideClearConfirm() {
      this.showClearDialog = false
    },
    
        async clearAllChats() {
      try {
      if (this.chatStore) {
          // 先清空本地数据
        this.chatStore.clearAllChats()
          
          // 可以选择是否同时清空服务器数据
          // 这里我们只清空本地，服务器数据保留
        }
        
        this.hideClearConfirm()
        uni.showToast({
          title: '已清空本地对话',
          icon: 'success'
        })
      } catch (error) {
        console.error('清空对话失败:', error)
        uni.showToast({
          title: '清空失败',
          icon: 'none'
        })
      }
    },

    // 清理空对话
    cleanEmptyChats() {
      try {
        if (this.chatStore) {
          const removedCount = this.chatStore.cleanEmptyChats()
          
      this.hideClearConfirm()
          
          if (removedCount > 0) {
      uni.showToast({
              title: `清理了 ${removedCount} 个空对话`,
        icon: 'success'
      })
          } else {
            uni.showToast({
              title: '没有发现空对话',
              icon: 'none'
            })
          }
        }
      } catch (error) {
        console.error('清理空对话失败:', error)
        uni.showToast({
          title: '清理失败',
          icon: 'none'
        })
      }
    },
    
    editChatTitle(chat) {
      this.editingChat = chat
      this.editingTitle = chat.title
      this.showEditDialog = true
    },
    
    hideEditDialog() {
      this.showEditDialog = false
      this.editingChat = null
      this.editingTitle = ''
    },
    
    confirmEditTitle() {
      if (this.editingChat && this.editingTitle.trim()) {
        if (this.chatStore) {
          this.chatStore.updateChatTitle(this.editingChat.id, this.editingTitle.trim())
        }
        this.hideEditDialog()
        uni.showToast({
          title: '标题已更新',
          icon: 'success'
        })
      } else {
        uni.showToast({
          title: '请输入有效标题',
          icon: 'none'
        })
      }
    },
    
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      // 小于1分钟
      if (diff < 60000) {
        return '刚刚'
      }
      // 小于1小时
      if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前'
      }
      // 小于24小时
      if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前'
      }
      // 小于7天
      if (diff < 604800000) {
        return Math.floor(diff / 86400000) + '天前'
      }
      // 其他情况显示日期
      return date.toLocaleDateString()
    }
  }
}
</script>

<style scoped>
.history-container {
  min-height: 100vh;
  height: 100vh;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  width: 100%;
  box-sizing: border-box;
  overflow-x: hidden;
  position: relative;
}

/* PC端特殊处理 - 确保历史页面占满整个屏幕 */
@media (min-width: 769px) {
  .history-container {
    height: 100vh;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
  }
  
  /* 确保内容区域能够填充剩余空间 */
  .chat-list {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    min-height: calc(100vh - 120px); /* 减去头部高度 */
  }
}

/* 顶部导航栏样式 */
.header {
  width: 100%;
  max-width: 600px;
  height: 50px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  border-bottom: 1px solid #e9ecef;
  border-radius: 20px 20px 0 0;
  box-sizing: border-box;
  margin: 0 auto;
}

.header-left, .header-right {
  width: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-center {
  flex: 1;
  text-align: center;
}

.app-name {
  font-size: 18px;
  font-weight: 600;
  color: #212529;
}

.back-icon, .clear-icon {
  font-size: 20px;
  color: #495057;
  cursor: pointer;
  font-weight: 400;
}

/* 小程序模式顶部样式 */
.mp-header {
  width: 100%;
  background-color: #fff;
  color: #000;
}

.mp-status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: calc(16px + env(safe-area-inset-top, 0px)) 16px 4px 16px;
  font-size: 14px;
  background: #fff;
  height: calc(28px + env(safe-area-inset-top, 0px));
}

.mp-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px 12px 16px;
  background: #faf8f8;
  border-bottom: 1px solid #333;
}

.mp-back, .mp-clear {
  font-size: 18px;
  color: #101010;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background 0.2s;
}

.mp-back:hover, .mp-clear:hover {
  background: rgba(255, 255, 255, 0.1);
}

.mp-title {
  font-size: 16px;
  font-weight: 600;
  color: #101010;
}

/* 对话列表样式 */
.chat-list {
  flex: 1;
  width: 100%;
  max-width: 600px;
  padding: 16px;
  background: #f8f9fa;
  overflow-y: auto;
  box-sizing: border-box;
  margin: 0 auto;
  min-height: calc(100vh - 120px); /* 确保最小高度 */
  display: flex;
  flex-direction: column;
}

.chat-list-mp {
  max-width: 100%;
  padding: 12px;
  background: #f0f0f0;
}

.chat-item {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
  cursor: pointer;
}

.chat-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.chat-item-active {
  border-color: #667eea;
  background: #f8f9ff;
}

.chat-item-content {
  flex: 1;
  min-width: 0;
}

.chat-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-preview {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: #666;
}

.chat-message-count {
  color: #667eea;
}

.chat-time {
  color: #999;
}

.chat-actions {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.chat-item:hover .chat-actions {
  opacity: 1;
}

.action-icon {
  font-size: 16px;
  padding: 4px;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.2s ease;
}

.action-icon:hover {
  background: #f0f0f0;
}

/* 空状态样式 */
.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 30px;
}

.start-chat-btn {
  background: #667eea;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.3s ease;
}

.start-chat-btn:hover {
  background: #5a6fd8;
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-content {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.dialog-header {
  margin-bottom: 16px;
}

.dialog-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.dialog-body {
  margin-bottom: 24px;
}

.dialog-message {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.title-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  box-sizing: border-box;
}

.dialog-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.dialog-actions-row {
  display: flex;
  gap: 12px;
  justify-content: space-between;
}

.dialog-btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  border: none;
  transition: background 0.2s ease;
}

.dialog-btn-cancel {
  background: #f0f0f0;
  color: #666;
}

.dialog-btn-cancel:hover {
  background: #e0e0e0;
}

.dialog-btn-sync {
  background: #42a5f5;
  color: #fff;
}

.dialog-btn-sync:hover {
  background: #1e88e5;
}

.dialog-btn-clean {
  background: #ffa726;
  color: #fff;
}

.dialog-btn-clean:hover {
  background: #fb8c00;
}

.dialog-btn-confirm {
  background: #667eea;
  color: #fff;
}

.dialog-btn-confirm:hover {
  background: #5a6fd8;
}

/* 响应式断点样式 */
@media (min-width: 481px) {
  .history-container {
    max-width: 720px;
    margin: 0 auto;
  }
  
  .chat-list {
    max-width: 680px;
  }
}

@media (min-width: 769px) {
  .history-container {
    max-width: 820px;
    margin: 0 auto;
  }
  
  .chat-list {
    max-width: 780px;
  }
}

@media (min-width: 1025px) {
  .history-container {
    max-width: 960px;
    margin: 0 auto;
  }
  
  .chat-list {
    max-width: 920px;
  }
}
</style> 